  //
//  GHLoginViewController.m
//  GodHorses
//
//  Created by Mac on 2017/11/14.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "TMGLoginViewController.h"
#import "UITextField+STInputLimit.h"
#import "TMGoldTabbarViewController.h"
#import "TMGResetPwdViewController.h"
#import "TMGRegisterViewController.h"
#import "AppDelegate.h"
#define textFiledBackgroundColor [UIColor colorWithRed:77/255.0 green:96/255.0 blue:129/255.0 alpha:1]
@interface TMGLoginViewController ()
@property(nonatomic, strong) UITextField                     *accountTextFiled;
@property(nonatomic, strong) UITextField                     *pwdTextFiled;
@property(nonatomic, strong) STButton                     *desButton;
@end

@implementation TMGLoginViewController
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    [self configSubView];
    [self addNotifacations];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self st_hideNavagetionbarAnimated:animated];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self st_showNavagationbarAnimated:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFieldTextDidChangeNotification:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
}
- (void)textFieldTextDidChangeNotification:(NSNotification*)notify{
    if (notify.object == self.pwdTextFiled) {
        [self.pwdTextFiled st_textInputLimitWithLength:16];
    }else if (notify.object == self.accountTextFiled){
        [self.accountTextFiled st_textInputLimitWithLength:11];
    }
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark --subView
- (void)configSubView{

    UIImageView * iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 206)];
    iconImageView.image = [UIImage imageNamed:@"logo-1"];
    iconImageView.st_centerX = UIScreenWidth /2;
    [self.view addSubview:iconImageView];
    

    
    UIView * accountView = [self configAccountTextFiled];
    accountView.st_top = iconImageView.st_bottom + 80;
    [self.view addSubview:accountView];
    
    UIView * pwdView = [self configpwdTextFiled];
    pwdView.st_top = accountView.st_bottom + 20;
    [self.view addSubview:pwdView];
    
    STButton * desButton = [[STButton alloc] initWithFrame:CGRectMake(17, 0, 44, 44)
                                                     title:@""
                                                titleColor:TM_secendTextColor
                                                 titleFont:13
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"icon_选中"]];
    [desButton setImage:[UIImage imageNamed:@"icon_未选中"] forState:UIControlStateSelected];
    self.desButton = desButton;
    [desButton setClicAction:^(UIButton *sender) {
        sender.selected = !sender.selected;
    }];
    desButton.selected = YES;
    desButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.view addSubview:desButton];
    desButton.top = pwdView.bottom;
    
     __weak typeof(self) weakSelf =  self;
    STButton *titleButton = [[STButton alloc] initWithFrame:CGRectMake(desButton.right, 0, UIScreenWidth, 44)
                                                      title:@"我已经认真阅读并同意黄金口袋登录协议"
                                                 titleColor:TM_secendTextColor
                                                  titleFont:13
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:nil];
    [titleButton setAttributedTitle:[titleButton.currentTitle st_convertAttributeStringWithKeyWord:@"黄金口袋登录协议" attributes:@{NSForegroundColorAttributeName:TM_orangeColor}] forState:UIControlStateNormal];
    [titleButton setClicAction:^(UIButton *sender) {
        
        NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/contract?cate=%@",
                          @"7"];
        STWebViewController * webvc = [[STWebViewController alloc] initWithUrl:url];
        webvc.progressBackgroundColor = [UIColor whiteColor];
        webvc.progressTintColor = TM_orangeColor;
        webvc.forceTitle = @"登录协议";
        [weakSelf.navigationController pushViewController:webvc animated:YES];
    }];
    titleButton.centerY = desButton.centerY;
    [self.view addSubview:titleButton];
    
    
   
    STButton * loginButton = [[STButton alloc] initWithFrame:CGRectMake(30, pwdView.st_bottom + 40, UIScreenWidth - 60, 44)
                                                       title:@"登录"
                                                  titleColor:[UIColor whiteColor]
                                                   titleFont:18
                                                cornerRadius:22
                                             backgroundColor:TM_orangeColor
                                             backgroundImage:nil
                                                       image:nil];
    loginButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [loginButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedLoginButton];
    }];
    [self.view addSubview:loginButton];
    
    STButton * forgotButton = [[STButton alloc] initWithFrame:CGRectMake(30 + 22, loginButton.st_bottom + 20, 100, 44)
                                                        title:@"忘记密码?"
                                                   titleColor:TM_secendTextColor
                                                    titleFont:13
                                                 cornerRadius:0
                                              backgroundColor:[UIColor clearColor]
                                              backgroundImage:nil
                                                        image:nil];
    forgotButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [forgotButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedforgotButton];
    }];
    [self.view addSubview:forgotButton];
    
    STButton * registerButton = [[STButton alloc] initWithFrame:CGRectMake(30, loginButton.st_bottom + 20, 100, 44)
                                                          title:@"立即注册"
                                                     titleColor:TM_secendTextColor
                                                      titleFont:13
                                                   cornerRadius:0
                                                backgroundColor:[UIColor clearColor]
                                                backgroundImage:nil
                                                          image:nil];
    registerButton.st_right = loginButton.st_right - 22;
    registerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [registerButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedregisterButton];
    }];
    [self.view addSubview:registerButton];
    
    //copyRight
    STLabel * commpanyLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, UIScreenWidth - 30 , 13)
                                                        text:@"四川昆仑电子商务有限公司"
                                                   textColor:[UIColor whiteColor]
                                                        font:12
                                                 isSizetoFit:NO
                                               textAlignment:NSTextAlignmentCenter];
    commpanyLable.st_centerX = UIScreenWidth / 2;
    //[self.view addSubview:commpanyLable];
    STLabel * copyLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, UIScreenWidth - 30, 13)
                                                    text:@"Sichuan kunlun electronic business limited"
                                               textColor:[UIColor whiteColor]
                                                    font:12
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentCenter];
    copyLable.st_centerX = UIScreenWidth / 2;
    copyLable.st_bottom = UIScreenHeight - 20 ;
    commpanyLable.st_bottom = copyLable.st_top - 5;
   // [self.view addSubview:copyLable];
}
- (UIView*)configAccountTextFiled{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(30, 0, UIScreenWidth - 60, 44)];
    view.backgroundColor = [UIColor whiteColor];
    [view st_showBottomLine];
    UITextField * textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, view.st_width - 0, 43)];
    textFiled.placeholder = @"用户名/手机号";
    textFiled.keyboardType = UIKeyboardTypeNumberPad;
    UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 ,25, 44)];
    UIImageView * leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 3, 14, 18)];
    leftImageView.centerY = leftView.height / 2;
    leftImageView.image = [UIImage imageNamed:@"icon_6.01yonghuming"];
    [leftView addSubview:leftImageView];
    textFiled.leftView = leftView;
    textFiled.leftViewMode = UITextFieldViewModeAlways;
    textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    textFiled.textColor = TM_secendTextColor;
    textFiled.backgroundColor =  [UIColor whiteColor];;
    [view addSubview:textFiled];
    self.accountTextFiled = textFiled;
    return view;
}
- (UIView*)configpwdTextFiled{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(30, 0, UIScreenWidth - 60, 44)];
    view.backgroundColor = [UIColor whiteColor];
    [view st_showBottomLine];
    UITextField * textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, view.st_width - 0, 43)];
    textFiled.placeholder = @"密码";
    UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 23, 44)];
    UIImageView * leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 3, 12, 15)];
    leftImageView.image = [UIImage imageNamed:@"密码"];
    leftImageView.centerY = leftView.height / 2;
    [leftView addSubview:leftImageView];
    textFiled.leftView = leftView;
    textFiled.textColor = TM_secendTextColor;
    textFiled.backgroundColor = [UIColor whiteColor];
    textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    textFiled.keyboardType = UIKeyboardTypeASCIICapable;
    textFiled.leftViewMode = UITextFieldViewModeAlways;
    [view addSubview:textFiled];
    textFiled.secureTextEntry = YES;
    self.pwdTextFiled = textFiled;
    return view;
}
#pragma mark --Action Method
- (void)onSelectedLoginButton{
    if (self.accountTextFiled.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (self.desButton.selected) {
        [SVProgressHUD showErrorWithStatus:@"请阅读并且同意黄金口袋登录协议"];
        return;
    }
    if (self.accountTextFiled.text.length != 11) {
        [SVProgressHUD showErrorWithStatus:@"手机号格式错误"];
        return;
    }
    if (self.pwdTextFiled.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    [SVProgressHUD showWithStatus:@"登录中"];
    [self loginWithMobie:self.accountTextFiled.text pwssWord:self.pwdTextFiled.text];
}
- (void)onSelectedforgotButton{
    
    [self.navigationController pushViewController:[TMGResetPwdViewController new] animated:YES];
}
- (void)onSelectedregisterButton{
    
    [self.navigationController pushViewController:[TMGRegisterViewController new] animated:YES];

}
- (void)onSelectedQQButton{
    
}
- (void)onSelectedWeChatButton{
    
}
- (void)onSelectedSinaButton{
    
}
#pragma mark --NetWork Method
- (void)loginWithMobie:(NSString *)mobile pwssWord:(NSString *)passWord{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (mobile.length) {
        [dic setObject:mobile forKey:@"mobile"];
    }else{
        NSLog(@"登录手机号为空");
        return;
    }
    if (passWord.length) {
        [dic setObject:passWord forKey:@"password"];
    }else{
        NSLog(@"登录密码为空");
        return;
    }
    AppDelegate * delegate = (id)[UIApplication sharedApplication].delegate;
    NSString * registrationID = delegate.registrationID;
    if (registrationID.length) {
        [dic setObject:registrationID forKey:@"registrationID"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:[NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/index/login"]
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                                                 NSString * token = responseObject[@"data"][@"token"];
                                                 NSNumber *  userId = responseObject[@"data"][@"id"];
                                                 TMGUserModel * user = [TMGUserModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 user.mobile = mobile;
                                                 [[STUserManger defult] updateUserModel:user];
                                                 [[STUserManger defult] updateToken:token];
                                                 [[STUserManger defult] updateUserID:userId.description];
                                                 [self loginIM];
                                                 [UIApplication sharedApplication].keyWindow.rootViewController = [TMGoldTabbarViewController new];
                                                 [self.view.window st_showAnimationWithType:STAnimationTyperippleEffect];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)loginIM{
    if ([STUserManger defult].loginUser.mobile.length) {
        EMClient * client = [EMClient sharedClient];
        NSString * userName =[STUserManger defult].loginUser.mobile;
        NSString * pwd = @"123456";
        BOOL isSuccess = [client registerWithUsername:userName password:pwd];
        
        
        [client loginWithUsername:userName password:pwd completion:^(NSString *aUsername, EMError *aError) {
            //单聊
            NSLog(@"环信登录成功");
            [client.contactManager addContact:@"service_one" message:@"iOS 登录成功自动添加好友"];
            
            
        }];
    }
}
@end


